#!/usr/bin/env coffee

minimist = require('minimist')
args = minimist(process.argv.slice(2), {
    string:"file"
})

fs = require('fs')

CODE = zipFile: fs.readFileSync(
    args.file, 'base64'
)


CONFIG = require('../config/fc.coffee')
FCClient = require('@alicloud/fc2')
CLIENT = new FCClient(...CONFIG.FC)


create = (serviceName, functionName)->
    console.log 'CREATE SERVICE :', serviceName

    try
        resp = await CLIENT.createService(serviceName)
    catch err
        if err.code == 'ServiceAlreadyExists'
            console.log err.code
        else
            throw err

    console.log 'CREATE FUNCTION :', functionName
    resp = await CLIENT.createFunction(
        serviceName
        {
            functionName
            handler: 'fckoa/koa/fc.koa'
            initializer:'fckoa/koa/fc.init'
            memorySize: CONFIG.memorySize
            runtime: 'nodejs8'
            code:CODE
        }
    )


do ->
    [serviceName, functionName] = CONFIG.SERVICE_FUNCTION.split("/",2)
    try
        await CLIENT.updateFunction serviceName,functionName,code:CODE
    catch err
        if err.code.endsWith "NotFound"
            console.log err.code
            await create(serviceName, functionName)
        else
            throw err

